package com.sss.service.impl;

import com.sss.entity.SysUser;
import com.sss.mapper.SysUserMapper;
import com.sss.service.SysUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 用户信息表(SysUser)表服务实现类
 *
 * @author makejava
 * @since 2023-12-14 16:55:32
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public SysUser queryById(Long userId) {
        return this.sysUserMapper.queryById(userId);
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @Override
    public List<SysUser> queryByPage(Map<String, Object> map) {
        return this.sysUserMapper.queryAllByLimit(map);
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(SysUser sysUser) {
        return this.sysUserMapper.insert(sysUser);
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public int update(SysUser sysUser) {
        return this.sysUserMapper.update(sysUser);
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long userId) {
        return this.sysUserMapper.deleteById(userId) > 0;
    }

    @Override
    public SysUser loginSys(String username,String password) {
        SysUser user = sysUserMapper.loginSys(username,password);

       //重置最后登录时间
        //把最新时间赋给user
        user.setCreateTime(new Date());

        // 以下代码需要使用Springmvc,既控制层也需要由Spring托管,才会获得ip
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest( );

        //得到ip赋给user
        String ip = request.getRemoteAddr();
        user.setLoginIp(ip);

        //user执行更新，update在xml中是动态sql
        sysUserMapper.update(user);

        return user;
    }

    @Override
    public int deleteBatch(List<Integer> list) {
        return sysUserMapper.deleteBatch(list);
    }
}
